package com.zhiwei.msf.gateway.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;
import org.springframework.util.PathMatcher;
import org.springframework.util.StringUtils;

import com.zhiwei.msf.common.constant.CommonErrorConstants;
import com.zhiwei.msf.common.exception.BasePublishException;
import com.zhiwei.msf.common.service.GatewayService;
import com.zhiwei.msf.gateway.dao.entity.UserInfo;
import com.zhiwei.msf.gateway.service.UserTokenService;
import com.zhiwei.msf.gateway.service.WhiteListService;

/**
 * function 网关服务实现类 author zhiwei.yang time 2020-2-28-10:23
 */
@Service
@Order(Ordered.HIGHEST_PRECEDENCE)
public class GatewayServiceImpl implements GatewayService {

	@Autowired
	private UserTokenService userTokenService;
	@Autowired
	private WhiteListService whiteListService;
	@Autowired
	private PathMatcher pathMatcher;
	@Value("${spring.application.name}")
	private String application;

	@Override
	public String checkToken(String token) {
		if (StringUtils.isEmpty(token)) {
			throw new BasePublishException(CommonErrorConstants.PARAM_ERROR);
		}
		UserInfo userInfo = userTokenService.getUserInfoByToken(token);
		if (null == userInfo) {
			throw new BasePublishException(CommonErrorConstants.HTTP_TOKEN);
		}
		return userInfo.getUsername();
	}

	@Override
	public List<String> syncWhiteUrlList() {
		return whiteListService.queryValidWhiteList();
	}

	@Override
	public synchronized boolean checkWhiteUrl(String requestUri) {
		requestUri = requestUri.replaceAll("/" + application, "");
		List<String> whiteList = this.syncWhiteUrlList();
		for (String path : whiteList) {
			if (pathMatcher.match(path, requestUri)) {
				return true;
			}
		}
		return false;
	}
}